<?php 

// $Id$

// include simpleSAMLphp _autoload.php
require_once('/home/simplesaml/lib/_autoload.php');

SimpleSAML_Configuration::init('/home/simplesaml/config');#, 'simplesaml', 'config_moodle.php');
$session = SimpleSAML_Session::getInstance();

session_write_close();

require_once('../../config.php');

if(isset($_GET["logout"])) {
    simplesaml_logout($session);
} elseif(!isloggedin() && isguestuser()) {
    // not sure if we need thos one... guest user to be threated differently?
    simplesaml_init($session);
} elseif(!isloggedin()) {
    simplesaml_init($session);
} else {
    header('Location: '.$GLOBALS['CFG']->wwwroot);
}


function simplesaml_logout($session) {
    $config = SimpleSAML_Configuration::getInstance();
    if($session->isValid('saml2')) {
        SimpleSAML_Utilities::redirect('/' . $config->getValue('baseurlpath') . 'saml2/sp/initSLO.php?RelayState=' . urlencode($GLOBALS['CFG']->wwwroot));
    } else {
        header('Location: '.$GLOBALS['CFG']->wwwroot);
    }
}


function simplesaml_init($session) {
    $config = SimpleSAML_Configuration::getInstance();
    $pluginconfig = get_config('auth/feide');

    if (!$session->isValid('saml2')) { # 
        // not valid session. Ship user off to Feide
        SimpleSAML_Utilities::redirect('/'.$config->getValue('baseurlpath').'saml2/sp/initSSO.php', array('RelayState' => SimpleSAML_Utilities::selfURL(), 'idpentityid' => $pluginconfig->entityid,));
    } else {
        // Valid session. Register or update user in Moodle, log him on, and redirect to Moodle front
        
        // we require the plugin to know that we are now doing a feide login in hook puser_login 
        $GLOBALS['feide_login'] = TRUE;
        
        // get Feide values
        $attributes = $session->getAttributes();
        
        // make variables accessible to feide->get_userinfo. Information will be requested from authenticate_user_login -> create_user_record / update_user_record
        $GLOBALS['feide_login_attributes'] = $attributes;
        
        // just passes time as a password. User will never log in directly to moodle with this password anyway or so we hope?
        $GLOBALS['USER'] = authenticate_user_login($attributes['mail'][0], time());
        $GLOBALS['USER']->loggedin = true;
        $GLOBALS['USER']->site     = $CFG->wwwroot;
        
        update_user_login_times();
        
        if($pluginconfig->notshowusername) {
            // Don't show username on login page
            set_moodle_cookie('nobody');
        }

        set_login_session_preferences();
        add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
        check_enrolment_plugins($GLOBALS['USER']);
        load_all_capabilities();

        // just fast copied this from some other module - might not work...
        if (isset($GLOBALS['SESSION']->wantsurl) and (strpos($GLOBALS['SESSION']->wantsurl, $GLOBALS['CFG']->wwwroot) === 0)) {
            $urltogo = $SESSION->wantsurl;
        } else {
            $urltogo = $GLOBALS['CFG']->wwwroot.'/';
        }
        unset($GLOBALS['SESSION']->wantsurl);
        redirect($urltogo);
    }
}

?>
